/**
 * Tool Call Visualization Component
 * 
 * Displays tool calls made by the agent with parameters and results
 */

import { useState } from 'react';
import { Wrench, ChevronDown, ChevronUp, CheckCircle2, XCircle, Clock } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

export interface ToolCall {
  id: string;
  name: string;
  status: 'pending' | 'running' | 'success' | 'error';
  startTime: Date;
  endTime?: Date;
  parameters?: any;
  result?: any;
  error?: string;
}

interface ToolCallVisualizationProps {
  toolCalls: ToolCall[];
}

export function ToolCallVisualization({ toolCalls }: ToolCallVisualizationProps) {
  const [expandedCalls, setExpandedCalls] = useState<Set<string>>(new Set());

  const toggleCall = (id: string) => {
    setExpandedCalls((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  const getStatusIcon = (status: ToolCall['status']) => {
    switch (status) {
      case 'pending':
        return <Clock className="w-4 h-4 text-muted-foreground" />;
      case 'running':
        return <Clock className="w-4 h-4 text-blue-500 animate-pulse" />;
      case 'success':
        return <CheckCircle2 className="w-4 h-4 text-green-500" />;
      case 'error':
        return <XCircle className="w-4 h-4 text-red-500" />;
    }
  };

  const getStatusBadge = (status: ToolCall['status']) => {
    const colors: Record<ToolCall['status'], string> = {
      pending: 'bg-gray-500',
      running: 'bg-blue-500',
      success: 'bg-green-500',
      error: 'bg-red-500',
    };

    const labels: Record<ToolCall['status'], string> = {
      pending: '等待中',
      running: '执行中',
      success: '成功',
      error: '失败',
    };

    return (
      <Badge className={`${colors[status]} text-white text-xs`}>
        {labels[status]}
      </Badge>
    );
  };

  const formatDuration = (call: ToolCall) => {
    if (!call.endTime) return '-';
    const duration = call.endTime.getTime() - call.startTime.getTime();
    return `${duration}ms`;
  };

  if (toolCalls.length === 0) {
    return null;
  }

  return (
    <div className="space-y-2">
      <div className="text-sm font-semibold text-muted-foreground flex items-center gap-2">
        <div className="p-1.5 rounded-md bg-primary/10">
          <Wrench className="w-4 h-4 text-primary" />
        </div>
        工具调用
      </div>

      <div className="space-y-2">
        {toolCalls.map((call) => {
          const isExpanded = expandedCalls.has(call.id);
          return (
            <Card key={call.id} className="overflow-hidden group hover:border-primary/30 transition-all">
              <CardContent className="p-0">
                <div
                  className="flex items-start justify-between cursor-pointer p-3 hover:bg-accent/50 transition-colors"
                  onClick={() => toggleCall(call.id)}
                >
                  <div className="flex items-start gap-3 flex-1">
                    <div className={cn(
                      "p-2 rounded-lg shrink-0",
                      call.status === 'success' && "bg-green-500/10",
                      call.status === 'error' && "bg-red-500/10",
                      call.status === 'running' && "bg-blue-500/10",
                      call.status === 'pending' && "bg-gray-500/10"
                    )}>
                      {getStatusIcon(call.status)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap mb-1">
                        <span className="font-mono text-sm font-medium">
                          {call.name}
                        </span>
                        {getStatusBadge(call.status)}
                        {call.endTime && (
                          <span className="text-xs text-muted-foreground font-mono">
                            {formatDuration(call)}
                          </span>
                        )}
                      </div>

                      {call.error && (
                        <div className="text-xs text-destructive mt-1 p-2 bg-destructive/10 rounded">
                          {call.error}
                        </div>
                      )}
                    </div>
                  </div>

                  <Button variant="ghost" size="icon" className="h-6 w-6 shrink-0 opacity-60 group-hover:opacity-100 transition-opacity">
                    {isExpanded ? (
                      <ChevronUp className="w-4 h-4" />
                    ) : (
                      <ChevronDown className="w-4 h-4" />
                    )}
                  </Button>
                </div>

                {isExpanded && (
                  <div className="border-t p-3 space-y-3 bg-muted/20">
                    {/* Parameters */}
                    {call.parameters && (
                      <div>
                        <div className="text-xs font-semibold text-muted-foreground mb-2 flex items-center gap-1.5">
                          <span className="w-1 h-4 bg-primary rounded-full"></span>
                          参数
                        </div>
                        <div className="bg-background/50 p-3 rounded-lg border border-border">
                          <pre className="overflow-x-auto text-xs font-mono">
                            {JSON.stringify(call.parameters, null, 2)}
                          </pre>
                        </div>
                      </div>
                    )}

                    {/* Result */}
                    {call.result && (
                      <div>
                        <div className="text-xs font-semibold text-muted-foreground mb-2 flex items-center gap-1.5">
                          <span className="w-1 h-4 bg-green-500 rounded-full"></span>
                          结果
                        </div>
                        <div className="bg-background/50 p-3 rounded-lg border border-border">
                          <pre className="overflow-x-auto text-xs font-mono">
                            {typeof call.result === 'string'
                              ? call.result
                              : JSON.stringify(call.result, null, 2)}
                          </pre>
                        </div>
                      </div>
                    )}

                    {/* Timing */}
                    <div className="text-xs text-muted-foreground/80 flex items-center gap-4 pt-2 border-t">
                      <span className="flex items-center gap-1.5">
                        <span className="text-muted-foreground/60">开始:</span>
                        <span className="font-mono">{call.startTime.toLocaleTimeString()}</span>
                      </span>
                      {call.endTime && (
                        <span className="flex items-center gap-1.5">
                          <span className="text-muted-foreground/60">结束:</span>
                          <span className="font-mono">{call.endTime.toLocaleTimeString()}</span>
                        </span>
                      )}
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
